package nimble.unionpay.openapi;

import com.alibaba.fastjson.JSONObject;
import nimble.json.FastjsonUtils;
import nimble.net.HttpUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

public abstract class UnionPayOpenApi {

    public enum ApiMode {
        test, product
    }

    protected Logger logger;

    protected ApiMode apiMode;

    protected String appId;

    protected String appSecret;

    protected String secret;

    protected String token;

    protected String requestUrl;

    protected String tokenUrl;

    private String tokenQueryUrl;

    private int expireIn;

    private Date tokenExpireTime;

    public UnionPayOpenApi(String appId, String appSecret,String secret) {
        this(ApiMode.product, appId, appSecret,secret);
    }

    public UnionPayOpenApi(ApiMode apiMode, String appId, String appSecret,String secret) {
        this.apiMode = apiMode;
        this.appId = appId;
        this.appSecret = appSecret;
        this.secret=secret;
        //
        logger = LoggerFactory.getLogger(this.getClass());
    }

    public void buildTokenQueryUrl() {
        tokenQueryUrl = tokenUrl.concat("?app_id=").concat(appId).concat("&app_secret=").concat(appSecret);
    }

    protected boolean getToken() {
        // 判断token是否过期
        if (StringUtils.isNotBlank(token)&& ObjectUtils.allNotNull(tokenExpireTime)) {
            if(tokenExpireTime.getTime()>new Date().getTime())
            {
                return true;
            }
        }
        try {
            String response = HttpUtils.getString(tokenQueryUrl);
            if (StringUtils.isBlank(response)) {
                return false;
            }
            JSONObject jo = FastjsonUtils.parseObject(response);
            String respMsg = jo.getString("respMsg");
            String respCd = jo.getString("respCd");
            if (!StringUtils.equals(respCd, "0000")) {
                logger.error("获取token失败：{}[{}]", respMsg, respCd);
                return false;
            }
            token = jo.getString("token");
            expireIn = jo.getInteger("expire_in");
            tokenExpireTime=DateUtils.addSeconds(new Date(),expireIn);
            return true;
        } catch (Exception e) {
            logger.info("{}", e);
            return false;
        }
    }
}
